package tree;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @ Author     ：侯耀祖
 * @ Description：
 */
public class connect {
    public Node connect(Node root) {
        Deque<Node> que = new LinkedList<>();
        if (root == null){
            return root;
        }
        que.offer(root);
        while (!que.isEmpty()){
            int len = que.size();
            for (int i = 0; i < len; i++) {
                Node item = que.pollFirst();
                if (i == len-1){
                    item.next = null;
                } else {
                    item.next = que.peekFirst();
                }

                if (item.left != null){
                    que.offerLast(item.left);
                }
                if (item.right != null){
                    que.offerLast(item.right);
                }
            }
        }
        return root;
    }
}
